/*
 *  Copyright 2013 National Institute of Advanced Industrial Science and Technology
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.sss.mapreduce.datatype;

import java.util.Arrays;

import org.sss.util.BytesComparator;

/**
 * A Packable class that encapsulates a byte[] object.
 */
public class PackableBytes implements Packable {
  private static final byte[] EMPTY_BYTES = {};
  private byte[] bytes;
  /**
   * Initialize a newly created PackableBytes object so that it represents an
   * empty byte sequence.
   */
  public PackableBytes() { this(EMPTY_BYTES); }
  /**
   * Create a PackableBytes using the byte array as the initial value.
   * @param bytes this array becomes the backing storage for the object.
   */
  public PackableBytes(byte[] bytes) {
    if (bytes == null) { bytes = EMPTY_BYTES; }
    this.bytes = bytes;
  }
  /**
   * Returns the byte array held in this object.
   * @return the byte array held in this object.
   */
  public byte[] get() { return bytes; }
  /**
   * Indicates whether some other object is "equal to" this one.
   * see {@link Packable#equals}
   */
  @Override
  public boolean equals(Object o) {
    if (o instanceof PackableBytes) {
      if (o == this) {
        return true;
      }
      byte[] other = ((PackableBytes) o).get();
      return BytesComparator.compare(bytes, 0, bytes.length, other, 0, other.length) == 0;
    }
    else {
      return false;
    }
  }
  /**
   * Returns a hash code value for the object.
   * see {@link Packable#hashCode}
   */
  @Override
  public int hashCode() {
    return Arrays.hashCode(bytes);
  }
  /**
   * Indicates which slot this object should be put.
   * see {@link Packable#slot}
   */
  @Override
  public int slot() {
    return this.hashCode();
  }

  @Override
  public long getRoughSize() {
    return 16 + bytes.length;
  }
}
